import socket
import time
import sys
import tty
import termios

# 创建 socket 对象
client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

# 定义服务器的 IP 地址和端口号
host = '192.168.35.117'  # 服务端的 IP 地址
port = 8080             # 服务端的端口

# 连接到服务器
try:
    client_socket.connect((host, port))
    print("已连接到服务器")
except Exception as e:
    print(f"连接失败: {e}")
    exit(1)

# 保存原始终端设置
old_settings = termios.tcgetattr(sys.stdin)
try:
    tty.setcbreak(sys.stdin.fileno())  # 设置为字符模式

    print("输入指令:")
    print("w - 前进")
    print("s - 后退")
    print("a - 停止")
    print("z - 站立")
    print("x - 蹲下")
    print("m - 持续发送 3 秒的前进指令")
    print("q - 退出")

    def send_message(msg):
        global client_socket  # 声明 client_socket 是全局变量
        try:
            client_socket.sendall(msg.encode('utf-8'))
            print(f"已发送消息: {msg.strip()}")
        except BrokenPipeError:
            print("连接已断开，尝试重新连接...")
            # 尝试重新连接
            client_socket.close()
            client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            try:
                client_socket.connect((host, port))
                print("已重新连接到服务器")
            except Exception as e:
                print(f"重新连接失败: {e}")
                time.sleep(1)

    while True:
        # 获取键盘输入的单个字符
        char = sys.stdin.read(1)

        # 根据输入的字符构造不同的控制消息
        if char == 'w':
            message = "linear x: 0.5, angular z: 0.0\n"
        elif char == 's':
            message = "linear x: -0.5, angular z: 0.0\n"
        elif char == 'a':
            message = "linear x: 0.0 angular z: 0.0\n"
        elif char == 'z':
            message = "linear x: 0.0, angular z: 0.0, action: 1\n"
        elif char == 'x':
            message = "linear x: 0.0, angular z: 0.0 action,: 0\n"
        elif char == 'm':
            # 按下 m 键时持续发送 3 秒的前进指令
            print("开始持续发送前进指令，持续 3 秒")
            start_time = time.time()
            while time.time() - start_time < 3:
                message1 = "linear x: 0.5, angular z: 0.0\n"
                send_message(message1)
                time.sleep(0.1)  # 控制发送频率
            print("已持续发送前进指令 3 秒")
            continue  # 跳过发送消息的代码
        elif char == 'q':
            print("退出程序")
            break
        else:
            print(f"无效输入: {char}")
            continue

        # 发送消息
        send_message(message)

except KeyboardInterrupt:
    print("\n客户端正在关闭...")
finally:
    # 恢复原始终端设置
    termios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)
    client_socket.close()
    print("连接已关闭")